//
//  ZSMineViewController.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/8.
//

import UIKit
import ProgressHUD

class ZSMineViewController: ZSBaseViewController {

    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var tipsLabel: UILabel!
    @IBOutlet weak var signButton: UIButton!
    @IBOutlet weak var openMenberView: UIView!
    @IBOutlet weak var openMenberHeight: NSLayoutConstraint!
    @IBOutlet weak var openMenberTop: NSLayoutConstraint!
    @IBOutlet weak var receiveMenber: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hexString: "#F0F3FD")
        navigationHeight.constant = UIApplication.shared.statusBarFrame.size.height + 44
        NotificationCenter.default.addObserver(self, selector: #selector(subscriptionReloadData(_:)), name: NSNotification.Name(rawValue: "ZSSubscriptionReloadData"), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let bundleID = Bundle.main.bundleIdentifier {
            fetchSubscriptionPrice(buildId: bundleID)
        }
    }
    
    @objc func subscriptionReloadData(_ sender: NotificationCenter) {
        if let bundleID = Bundle.main.bundleIdentifier {
            fetchSubscriptionPrice(buildId: bundleID)
        }
    }
    
    @IBAction func goSignIn(_ sender: UIButton) {
        guard let signDict = UserDefaults.standard.object(forKey: zsSignData) as? Dictionary<String, Any> else {
            let dict = [
                "date": Date(),
                "number": 3,
            ] as [String : Any]
            UserDefaults.standard.set(dict, forKey: zsSignData)
            tipsLabel.isHidden = true
            signButton.isHidden = true
            self.view.makeToast("签到成功", position: .center)
            return
        }
        
        if let signDate = signDict["date"] as? Date, let number = signDict["number"] as? Int {
            let calendar = Calendar.current
            let currentDateComponents = calendar.dateComponents([.year, .month, .day], from: Date())
            let targetDateComponents = calendar.dateComponents([.year, .month, .day], from: signDate)
            if currentDateComponents.year == targetDateComponents.year &&
                currentDateComponents.month == targetDateComponents.month &&
                currentDateComponents.day == targetDateComponents.day {
                return
            }
            let dict = [
                "date": Date(),
                "number": number + 3,
            ] as [String : Any]
            UserDefaults.standard.set(dict, forKey: zsSignData)
            tipsLabel.isHidden = true
            signButton.isHidden = true
            self.view.makeToast("签到成功", position: .center)
        }
    }
    
    @IBAction func didOpenMenber(_ sender: UITapGestureRecognizer) {
        let vc = ZSSubscriptionViewController()
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: false)
    }
    
    @IBAction func goUserAgreement(_ sender: UITapGestureRecognizer) {
        let vc = ZSWebViewController()
        vc.linkUrl = userProtocolLink
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func goPrivacyAgreement(_ sender: UITapGestureRecognizer) {
        let vc = ZSWebViewController()
        vc.linkUrl = privacyAgreementLink
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func goFeedback(_ sender: UITapGestureRecognizer) {
        let vc = ZSFeedbackViewController()
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: false)
    }
    
    
    @IBAction func receiveGuide(_ sender: UIButton) {
        let vc = ZSReceiveGuideViewController()
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: false)
        vc.receiveHandler = { [self] status in
            receiveMenber.isHidden = true
        }
    }
    
    func fetchSubscriptionPrice(buildId: String) {
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbserves/api/appdingyue/info"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }

        let parameters: [String: Any] = ["packageName": buildId]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                print("Error: \(error)")
                return
            }

            guard let data = data else {
                print("No data received")
                return
            }

            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let data = json["data"] as? Dictionary<String, Any>, let remark = data["remark"] as? String {
                    DispatchQueue.main.async {
                        if let orderid = UserDefaults.standard.object(forKey: "orderId") as? String, !orderid.isEmpty  {
                            self.tipsLabel.isHidden = true
                            self.signButton.isHidden = true
                            self.openMenberView.isHidden = true
                            self.openMenberHeight.constant = 0
                            self.openMenberTop.constant = 0
                            self.receiveMenber.isHidden = true
                            if let expiresDate = UserDefaults.standard.object(forKey: expiresDateIdentifier) as? Date {
                                let dateFormatter = DateFormatter()
                                dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                                dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                                dateFormatter.timeZone = TimeZone.current
                                let dateString = dateFormatter.string(from: expiresDate)
                                self.tipsLabel.isHidden = false
                                self.tipsLabel.text = dateString + "到期"
                            }else if let expiresDate = UserDefaults.standard.object(forKey: expiresDateIdentifier) as? String {
                                self.tipsLabel.isHidden = false
                                self.tipsLabel.text = expiresDate
                            }
                        }else {
                            if let signData = UserDefaults.standard.object(forKey: zsSignData) as? Dictionary<String, Any> {
                                if let signDate = signData["date"] as? Date {
                                    let calendar = Calendar.current
                                    let currentDateComponents = calendar.dateComponents([.year, .month, .day], from: Date())
                                    let targetDateComponents = calendar.dateComponents([.year, .month, .day], from: signDate)
                                    if currentDateComponents.year == targetDateComponents.year &&
                                        currentDateComponents.month == targetDateComponents.month &&
                                        currentDateComponents.day == targetDateComponents.day {
                                        self.tipsLabel.isHidden = true
                                        self.signButton.isHidden = true
                                    }else {
                                        self.tipsLabel.isHidden = false
                                        self.signButton.isHidden = false
                                    }
                                }else {
                                    if remark.contains("【活动中】") {
                                        self.tipsLabel.isHidden = false
                                        self.signButton.isHidden = false
                                    }else {
                                        self.tipsLabel.isHidden = true
                                        self.signButton.isHidden = true
                                    }
                                }
                            }else {
                                if remark.contains("【活动中】") {
                                    self.tipsLabel.isHidden = false
                                    self.signButton.isHidden = false
                                }else {
                                    self.tipsLabel.isHidden = true
                                    self.signButton.isHidden = true
                                }
                            }
                            self.openMenberView.isHidden = false
                            self.openMenberHeight.constant = 91
                            self.openMenberTop.constant = 23
                            guard let zsBenefitDate = UserDefaults.standard.object(forKey: zsBenefit) as? Date else {
                                if remark.contains("【活动中】") {
                                    self.receiveMenber.isHidden = false
                                }else {
                                    self.receiveMenber.isHidden = true
                                }
                                return
                            }
                            self.tipsLabel.isHidden = false
                            let dateFormatter = DateFormatter()
                            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                            dateFormatter.timeZone = TimeZone.current
                            let calendar = Calendar.current
                            let dateString = dateFormatter.string(from: calendar.date(byAdding: .day, value: 3, to: zsBenefitDate)!)
                            self.tipsLabel.isHidden = false
                            self.tipsLabel.text = dateString + "到期"
                            self.receiveMenber.isHidden = true
                        }
                    }
                }
                
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }

        task.resume()
    }
    
}
